<?php

namespace App\Http\Controllers\Client\Shop\Goods;

use App\Http\Controllers\ClientController;
use App\Models\Tools\AliOss;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GoodsListController extends ClientController
{
    /**
     * 查询霸王餐活动策略
     */
    public function index()
    {
        $all = $this->all;
        $shop_id = $all['shop_id'];

        try {
            // 查询店铺信息，是否已审核通过
            $shop_status = DB::table('shop')->where('shop_id', '=', $shop_id)->value('verified');

            $goods = DB::table('lottery_goods as lg')
                ->where('lg.creator', '=', $this->we_id)
                ->where('lg.shop_id', '=', $shop_id)
                ->select('lg.goods_id', 'lg.goods_name', 'lg.price', 'lg.title_img', 'lg.is_delete')
                ->get()
                ->map(function ($item) {
                    $item->title_img = AliOss::getUrl($item->title_img);
                    return $item;
                })
                ->toArray();
            $goods = json_decode(json_encode($goods), true);

            $goods_ids = Arr::pluck($goods, 'goods_id');

            $in_used = DB::table('lottery_activity')
                ->whereIn('goods_id', $goods_ids)
                ->groupBy('goods_id')
                ->select('goods_id')
                ->selectRaw('COUNT(*) as count')
                ->get()
                ->mapWithKeys(function ($item) {
                    return [$item->goods_id => $item->count];
                })
                ->toArray();
            $in_used = json_decode(json_encode($in_used), true);


            foreach ($goods as &$value) {
                $value['in_used'] = ($in_used[$value['goods_id']] ?? false) && true;
            }

            return $this->setReturnJson(0, 'success', ['goods' => $goods, 'shop' => $shop_status === 1]);
        } catch (\Exception $e) {
            Log::error(GoodsListController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '查询失败');
        }

    }

}
